/*
    Pureport, a report generator for Java
    Copyright (C) 2011  Maurice Perry <maurice@perry.ch>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package org.librebiz.pureport.context;

import bsh.EvalError;
import bsh.Interpreter;
import bsh.NameSpace;

public class ReportContext {
    private Interpreter interpreter = new Interpreter();
    private int scopeLevel = 0;

    public ReportContext() {
    }

    public void close() {
    }

    public void openScope() {
        interpreter.setNameSpace(
                new NameSpace(interpreter.getNameSpace(), "level" + scopeLevel));
        ++scopeLevel;
    }

    public void closeScope() {
        --scopeLevel;
        interpreter.setNameSpace(interpreter.getNameSpace().getParent());
    }

    public Object resolve(String name) {
        try {
            return interpreter.get(name);
        } catch (EvalError e) {
            throw new EvaluationException(e);
        }
    }

    public void define(String name, Object value) {
        try {
            interpreter.set(name, value);
        } catch (EvalError e) {
            throw new EvaluationException(e);
        }
    }

    public boolean evaluateCondition(String expr) {
        Object result = evaluate(expr);
        if (result instanceof Boolean) {
            return ((Boolean)result).booleanValue();
        } else {
            throw new EvaluationException("Boolean type required for " + expr);
        }
    }

    public Object evaluate(String expr) {
        try {
            System.out.println("Evaluate: " + expr);
            return interpreter.eval(expr);
        } catch (EvalError e) {
            throw new EvaluationException(e);
        }
    }

    public void execute(String statement) {
        try {
            System.out.println("Execute: " + statement);
            interpreter.eval(statement);
        } catch (EvalError e) {
            throw new EvaluationException(e);
        }
    }
}
